package com.shu.logsearch.util;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author Tree Cai
 * @date 2019/6/28
 */
public class MyJsonUtil {

    /**
     * 默认日期格式
     */
    public static final String DEFAULT_DATE_FORMATTER = "yyyy-MM-dd HH:mm:ss";

    /**
     * 将对象转为json字符串，当dateFormatter为null时，取默认日期格式DEFAULT_DATE_FORMATTER
     *
     * @param object
     * @param dateFormatter
     * @return
     * @throws JsonProcessingException
     */
    public static String json(Object object, String dateFormatter) throws JsonProcessingException {
        if (object == null)
            throw new NullPointerException("object 不能为null！");
        ObjectMapper objectMapper = new ObjectMapper();
        if (StringUtils.isEmpty(dateFormatter))
            dateFormatter = DEFAULT_DATE_FORMATTER;
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormatter);
        objectMapper.setDateFormat(sdf);
        return objectMapper.writeValueAsString(object);
    }

    /**
     * 将对象转为json字符串，使用默认日期格式DEFAULT_DATE_FORMATTER
     *
     * @param object
     * @return
     * @throws JsonProcessingException
     */
    public static String json(Object object) throws JsonProcessingException {
        return json(object, null);
    }

    /**
     * 将对象转化为key为属性，value为属性值的map对象
     *
     * @param object
     * @return
     */
    public static Map parseObject(Object object, String dateFormatter) {
        Assert.notNull(object);
        if (StringUtils.isEmpty(dateFormatter))
            dateFormatter = DEFAULT_DATE_FORMATTER;
        SerializeConfig mapper = new SerializeConfig();
        mapper.put(Date.class, new SimpleDateFormatSerializer(dateFormatter));
        return JSONObject.parseObject(JSONObject.toJSONString(object, mapper));
    }

    /**
     * 将对象转化为key为属性，value为属性值的map对象, 使用默认日期格式DEFAULT_DATE_FORMATTER
     *
     * @param object
     * @return
     */
    public static Map parseObject(Object object) {
        return parseObject(object, null);
    }
}
